//
//  QRCodeListController.swift
//  Order
//
//  Created by Lazyloading on 2020/7/14.
//  Copyright © 2020 lazyloading. All rights reserved.
//

import UIKit
import MGSwipeTableCell
import PKHUD

class QRCodeListController: UIViewController ,UITableViewDelegate,UITableViewDataSource,MGSwipeTableCellDelegate{
    
    let kQRCodeListCellID = "kQRCodeListCellID";
    
    var dataArray : [Any] = [];
    
    lazy var tableView : UITableView = {
        let table = UITableView.init(frame: self.view.bounds);
        
        table.backgroundColor = ZMColor.Gray.gray1;
        table.delegate = self;
        table.dataSource = self;
        table.registerNib("QRCodeListCell", kQRCodeListCellID);
        table.showsVerticalScrollIndicator = false;
        table.separatorStyle = .none;
//        table.estimatedRowHeight =  100;
        
        return table;
    }();
    
    lazy var addCode: UIButton = {
        let btn = UIButton.init();
        btn.backgroundColor = ZMColor.Orange.orange1;
        btn.addTarget(self, action: #selector(addCodeAction(button:)), for: .touchUpInside);
        btn.layer.cornerRadius = 10;
        btn.layer.masksToBounds = true;
        btn.setTitle("添加二维码", for: .normal);
        btn.titleLabel?.font = UIFont.init(fontType: .medium, fontSize: 16);
        return btn;
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.loadDefaultSetting();
        self.initSubViews();
        
    }
    
    // MARK: 👉🏻 🐷Life cycle🐷
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated);
        self.listDataRequest();
    }
    // MARK: 👉🏻 🐷System Delegate🐷
    // MARK: 👉🏻 🐷UITableView Delegate🐷
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count;
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 80;
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell : QRCodeListCell = tableView.dequeueReusableCell(withIdentifier: kQRCodeListCellID) as! QRCodeListCell;
        let model = self.dataArray[indexPath.row] as! QRCodeListModel;
        cell.contentLabel.text = model.account;
        cell.accountLabel.text = model.methodName;
        cell.icon.kf.setImage(with: URL.init(string: model.codeImgUrl()));
        cell.delegate = self;
        weak var weakSelf = self;

        let button = MGSwipeButton(title: "删除", backgroundColor: .red) { (cell : MGSwipeTableCell) -> Bool in
            weakSelf?.deleteQRCodeRequest(model: model);
            return true;
        }
        button.frame = CGRect.init(x: 0, y: 0, width: 90, height: 80);
        cell.rightButtons = [button];
        return cell;
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    }
    
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true;
    }
    
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
        return .delete;
    }
    
    func swipeTableCell(_ cell: MGSwipeTableCell, canSwipe direction: MGSwipeDirection, from point: CGPoint) -> Bool {
        if direction == .rightToLeft {
            return true;
        }
        return false;
    }
    

    // MARK: 👉🏻 🐷Event  Response🐷
    @objc func addCodeAction(button : UIButton){
        let vc = AddQRCodeController();
    
        self.navigationController?.pushViewController(vc, animated: true);
        
    }
    func listDataRequest()  {
        let param = ["" : ""];
        
        MoyaRequest(.qrCodeList(param), success: { (response : BaseResponse<[QRCodeListModel]>) in
            if response.respCode == 200{
                self.dataArray = response.data!;
                self.tableView.reloadData();
            }else{
                
            }
        }) { (error) in
            
        }
    }
    // MARK: 👉🏻 🐷Private Methods🐷
    func deleteQRCodeRequest(model : QRCodeListModel)  {
        weak var weakSelf = self;
        let param = [
            "id" : model.id ?? ""
        ];
        MoyaRequest(.deleteQRCode(param), success: { (response : BaseResponse<[String:Any]>) in
            if response.respCode == 200 {
                weakSelf?.listDataRequest();
            }else{
                HUD.flash(.label(response.respMessage), delay: 1);
                
            }
        }) { (error) in
            HUD.flash(.label("删除失败，请稍后再试"), delay: 1);        };
    }
    // MARK: 👉🏻 🐷Lazy loading🐷
    // MARK: 👉🏻 🐷Init SubViews🐷
    func loadDefaultSetting()  {
        self.view.backgroundColor = ZMColor.Gray.gray1;
        self.navigationItem.title = "二维码";
    }
    
    func initSubViews()  {
        self.view.addSubview(self.tableView);
        self.view.addSubview(self.addCode);
        
        
        self.layout();
    }
    
    func layout() {
        
        self.tableView.snp.makeConstraints { (make) in
            make.leading.trailing.top.equalToSuperview();
            make.bottom.equalTo(self.addCode.snp.top).offset(5);
        };
        
        self.addCode.snp.makeConstraints { (make) in
            make.leading.equalToSuperview().offset(20);
            make.trailing.equalToSuperview().offset(-20);
            make.height.equalTo(50);
            make.bottom.equalToSuperview().offset(-SafeBottom_H-25);
        };
    }


}
